import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/',
    component: () => import('@/views/layout/layout.vue'),
    children: [
      {
        path: '', // 子路由的path为空，则表示默认显示的路由组件
        component: () => import('@/views/home/home.vue')
      },
      {
        path: 'articles', // path前无 / (表示要拼接一级路由的路径，否则，反之)
        component: () => import('@/views/articles/articles.vue')
      },
      {
        path: 'image',
        component: () => import('@/views/image/image.vue')
      },
      {
        path: 'addArticle',
        component: () => import('@/views/addArticle/addArticle.vue')
      },
      {
        path: 'comment',
        component: () => import('@/views/comment/comment.vue')
      },
      {
        path: 'fans',
        component: () => import('@/views/fans/fans.vue')
      },
      {
        path: 'settings',
        component: () => import('@/views/settings/settings.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由全局前置守卫
// 如下页面是需要登陆之后才能访问的
const authPageList = ['/', '/comment', '/image', '/xxxxx']
router.beforeEach((to, from, next) => {
  console.log('发生了路由变化', from.path, '到', to.path)
  // 如果你要去的页面是主页，而你又没有登陆，则回到登陆页
  // if (to.path === '/' || to.path === '/content') {
  if (authPageList.includes(to.path)) {
    if (localStorage.getItem('TOKEN')) {
      next()
    } else {
      console.log('你要去的是主页，但是你并没有登陆，所以路由导航守卫把你送到的Login')
      next('/login')
    }
  } else {
    if (to.path === '/login' && localStorage.getItem('TOKEN')) {
      // 如果你已经登陆了，就不能访问login，直接跳到主页
      next('/')
    } else {
      next()
    }
  }
})

export default router
